<template>
  <div class="video-set-form-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>创建视频合集</h3>
          <span class="required-tip">带 <span class="red-star">*</span> 的字段为必填项</span>
        </div>
      </template>
      <el-form
          :model="videoSetForm"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          class="video-set-form"
      >
        <!-- 基础信息区域 -->
        <el-form-item label="合集封面" prop="cover_image">
          <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeUpload"
              accept="image/*"
          >
            <img v-if="videoSetForm.cover_image" :src="videoSetForm.cover_image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="合集标题" prop="title">
          <el-input
              v-model="videoSetForm.title"
              placeholder="请输入合集标题"
              maxlength="50"
              show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="合集描述" prop="description">
          <el-input
              v-model="videoSetForm.description"
              type="textarea"
              placeholder="请输入合集描述"
              :rows="4"
              maxlength="200"
              show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="合集分类" prop="category_id">
          <el-select
              v-model="videoSetForm.category_id"
              placeholder="请选择分类"
              filterable
              clearable
          >
            <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 章节内容区域 -->
        <el-form-item label="设置章节内容" prop="chapters">
          <el-collapse v-model="activeNames" accordion>
            <el-collapse-item name="1">
              <template #title>
                <span class="chapter-title">章节内容管理</span>
                <el-button
                    type="primary"
                    size="small"
                    @click="addChapter"
                    class="ml-2"
                >
                  <el-icon><Plus /></el-icon> 添加章节
                </el-button>
              </template>

              <div class="chapter-list">
                <el-card
                    class="chapter-item"
                    shadow="hover"
                    v-for="(chapter, index) in videoSetForm.chapters"
                    :key="chapter.id || index"
                >
                  <div class="chapter-header">
                    <el-input
                        v-model="chapter.title"
                        placeholder="请输入章节标题"
                        size="small"
                        class="chapter-title-input"
                    ></el-input>
                    <el-button
                        type="danger"
                        size="small"
                        @click="removeChapter(index)"
                        class="ml-2"
                    >
                      <el-icon><Delete /></el-icon> 删除
                    </el-button>
                  </div>

                  <div class="video-list">
                    <div class="video-item" v-for="(video, videoIndex) in chapter.videos" :key="videoIndex">
                      <el-input
                          v-model="video.title"
                          placeholder="视频标题"
                          size="small"
                          class="video-title-input"
                      ></el-input>
                      <el-input
                          v-model="video.url"
                          placeholder="视频地址/ID"
                          size="small"
                          class="video-url-input"
                      ></el-input>
                      <el-button
                          type="danger"
                          size="small"
                          @click="removeVideo(index, videoIndex)"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>

                    <el-button
                        type="primary"
                        size="small"
                        @click="addVideo(index)"
                        class="add-video-btn"
                    >
                      <el-icon><Plus /></el-icon> 添加视频
                    </el-button>
                  </div>
                </el-card>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>

      <div class="form-actions">
        <el-button
            type="primary"
            @click="onSubmit"
            :loading="submitLoading"
            class="submit-btn"
        >
          提交创建
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'

const formRef = ref(null)
const submitLoading = ref(false)
const activeNames = ref(['1'])

// 表单数据
const videoSetForm = reactive({
  title: '',
  cover_image: '',
  description: '',
  creator_id: null,
  category_id: null,
  chapters: [
    {
      id: null,
      title: '',
      videos: [
        {
          id: null,
          title: '',
          url: ''
        }
      ]
    }
  ],
  view_count: 0,
  like_count: 0,
  favorite_count: 0,
  is_featured: 0,
  is_curated: 0
})

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入合集标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在2-50个字符之间', trigger: 'blur' }
  ],
  cover_image: [
    { required: true, message: '请上传合集封面', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入合集描述', trigger: 'blur' },
    { min: 5, max: 200, message: '描述长度在5-200个字符之间', trigger: 'blur' }
  ],
  category_id: [
    { required: true, message: '请选择合集分类', trigger: 'change' }
  ]
})

// 模拟分类数据
const categories = ref([
  { id: 1, name: '科技' },
  { id: 2, name: '教育' },
  { id: 3, name: '娱乐' },
  { id: 4, name: '生活' },
  { id: 5, name: '游戏' },
  { id: 6, name: '美食' },
  { id: 7, name: '旅行' },
  { id: 8, name: '音乐' },
  { id: 9, name: '电影' },
  { id: 10, name: '其他' }
])

// 处理封面上传成功
const handleAvatarSuccess = (response, file, fileList) => {
  // 模拟上传成功，实际项目中应根据后端返回处理
  videoSetForm.cover_image = 'https://picsum.photos/1280/720?random=' + Math.random()
  ElMessage.success('封面上传成功')
}

// 上传前处理
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片')
    return false
  }

  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }

  return true
}

// 添加章节
const addChapter = () => {
  videoSetForm.chapters.push({
    id: null,
    title: '',
    videos: [
      {
        id: null,
        title: '',
        url: ''
      }
    ]
  })
}

// 删除章节
const removeChapter = (index) => {
  if (videoSetForm.chapters.length > 1) {
    videoSetForm.chapters.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一个章节')
  }
}

// 添加视频
const addVideo = (chapterIndex) => {
  videoSetForm.chapters[chapterIndex].videos.push({
    id: null,
    title: '',
    url: ''
  })
}

// 删除视频
const removeVideo = (chapterIndex, videoIndex) => {
  const chapter = videoSetForm.chapters[chapterIndex]
  if (chapter.videos.length > 1) {
    chapter.videos.splice(videoIndex, 1)
  } else {
    ElMessage.warning('至少保留一个视频')
  }
}

// 提交表单
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true

      // 模拟提交
      setTimeout(() => {
        console.log('表单数据:', videoSetForm)
        ElMessage.success('合集创建成功')
        submitLoading.value = false
      }, 1500)
    } else {
      ElMessage.error('请完善表单信息')
      return false
    }
  })
}
</script>

<style scoped>
.video-set-form-container {
  margin: 0 auto;
  padding: 0;
}

.form-card {
  border-radius: 8px;
  padding: 20px 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.required-tip {
  font-size: 12px;
  color: #999;
}

.red-star {
  color: #f56c6c;
}


.upload-cover-wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-cover-wrapper:hover {
  background-color: #ebedf0;
}

.upload-placeholder {
  text-align: center;
  color: #909399;
}

.upload-icon {
  font-size: 36px;
  margin-bottom: 10px;
}

.upload-tip {
  font-size: 12px;
  margin-top: 5px;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.chapter-list {
  margin-top: 15px;
}

.chapter-item {
  margin-bottom: 15px;
  padding: 15px;
}

.chapter-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.chapter-title-input {
  flex: 1;
  margin-right: 10px;
}

.video-list {
  padding: 10px 0;
}

.video-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.video-title-input {
  flex: 2;
  margin-right: 10px;
}

.video-url-input {
  flex: 3;
  margin-right: 10px;
}

.add-video-btn {
  margin-top: 5px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.submit-btn {
  width: 200px;
}
</style>
